import { ref, computed, onMounted, watch } from 'vue';

// 会话管理器 composable
export function useConversationManager() {
  // 响应式数据
  const conversations = ref([]);
  const currentConversationId = ref(null);
  const isLoading = ref(false);
  const error = ref(null);

  // 当前会话
  const currentConversation = computed(() => {
    return conversations.value.find(conv => conv.id === currentConversationId.value);
  });

  // 从localStorage加载会话
  const loadConversations = () => {
    try {
      const saved = localStorage.getItem('maess_conversations');
      if (saved) {
        const parsed = JSON.parse(saved);
        conversations.value = parsed.conversations || [];
        currentConversationId.value = parsed.currentId || null;
        
        // 如果没有当前会话且有会话列表，设置第一个为当前会话
        if (!currentConversationId.value && conversations.value.length > 0) {
          currentConversationId.value = conversations.value[0].id;
        }
      }
    } catch (err) {
      console.error('加载会话失败:', err);
    }
  };

  // 保存会话到localStorage
  const saveConversations = () => {
    try {
      localStorage.setItem('maess_conversations', JSON.stringify({
        conversations: conversations.value,
        currentId: currentConversationId.value
      }));
    } catch (err) {
      console.error('保存会话失败:', err);
    }
  };

  // 生成唯一ID
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  };

  // 从内容生成会话标题
  const generateTitle = (content) => {
    const maxLength = 20;
    return content.length > maxLength 
      ? content.substring(0, maxLength) + '...' 
      : content || '新会话';
  };

  // 创建新会话
  const createConversation = (initialContent = '') => {
    const newConversation = {
      id: generateId(),
      title: generateTitle(initialContent),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      messages: []
    };
    
    // 如果有初始内容，添加第一条消息
    if (initialContent) {
      addMessage(newConversation.id, 'user', initialContent);
    }
    
    conversations.value.unshift(newConversation);
    currentConversationId.value = newConversation.id;
    saveConversations();
    
    return newConversation;
  };

  // 删除会话
  const deleteConversation = (conversationId) => {
    const index = conversations.value.findIndex(conv => conv.id === conversationId);
    if (index !== -1) {
      conversations.value.splice(index, 1);
      
      // 如果删除的是当前会话，设置新的当前会话
      if (currentConversationId.value === conversationId) {
        currentConversationId.value = conversations.value.length > 0 
          ? conversations.value[0].id 
          : null;
        
        // 如果删除后没有会话了，创建一个新的默认会话
        if (!currentConversationId.value) {
          createConversation();
        }
      }
      
      saveConversations();
    }
  };

  // 重命名会话
  const renameConversation = (conversationId, newTitle) => {
    const conversation = conversations.value.find(conv => conv.id === conversationId);
    if (conversation) {
      conversation.title = newTitle.trim() || '未命名会话';
      conversation.updateTime = new Date().toISOString();
      
      // 更新会话顺序，将更新的会话移到顶部
      const index = conversations.value.indexOf(conversation);
      if (index > 0) {
        conversations.value.splice(index, 1);
        conversations.value.unshift(conversation);
      }
      
      saveConversations();
    }
  };

  // 切换会话
  const switchConversation = (conversationId) => {
    const conversation = conversations.value.find(conv => conv.id === conversationId);
    if (conversation) {
      currentConversationId.value = conversationId;
      
      // 更新会话顺序，将切换的会话移到顶部
      const index = conversations.value.indexOf(conversation);
      if (index > 0) {
        conversations.value.splice(index, 1);
        conversations.value.unshift(conversation);
      }
      
      saveConversations();
    }
  };

  // 添加消息
  const addMessage = (conversationId, role, content, status = 'completed', messageId = null) => {
    const conversation = conversations.value.find(conv => conv.id === conversationId);
    if (conversation) {
      const newMessage = {
        id: messageId || generateId(),
        role,
        content,
        timestamp: new Date().toISOString(),
        status
      };
      
      conversation.messages.push(newMessage);
      conversation.updateTime = new Date().toISOString();
      
      // 如果是用户的第一条消息，更新会话标题
      if (role === 'user' && conversation.messages.length === 1) {
        conversation.title = generateTitle(content);
      }
      
      // 更新会话顺序，将活跃的会话移到顶部
      const index = conversations.value.indexOf(conversation);
      if (index > 0) {
        conversations.value.splice(index, 1);
        conversations.value.unshift(conversation);
      }
      
      saveConversations();
      return newMessage;
    }
    return null;
  };

  // 更新消息
  const updateMessage = (conversationId, messageId, updates) => {
    const conversation = conversations.value.find(conv => conv.id === conversationId);
    if (conversation) {
      const message = conversation.messages.find(msg => msg.id === messageId);
      if (message) {
        Object.assign(message, updates);
        conversation.updateTime = new Date().toISOString();
        saveConversations();
      }
    }
  };

  // 清空所有会话
  const clearAllConversations = () => {
    conversations.value = [];
    currentConversationId.value = null;
    saveConversations();
    
    // 清空后创建一个新的默认会话
    createConversation();
  };

  // 监听会话变化，自动保存
  watch(
    () => conversations.value,
    () => {
      saveConversations();
    },
    { deep: true }
  );

  // 初始化时加载会话
  onMounted(() => {
    loadConversations();
    // 如果没有会话，创建一个新的默认会话
    if (conversations.value.length === 0) {
      createConversation();
    }
  });

  return {
    // 状态
    conversations,
    currentConversationId,
    currentConversation,
    isLoading,
    error,
    
    // 方法
    createConversation,
    deleteConversation,
    renameConversation,
    switchConversation,
    addMessage,
    updateMessage,
    clearAllConversations,
    loadConversations,
    saveConversations
  };
}